import axios from "axios";
import { message } from "antd";

// 创建实例时配置默认值
const http = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
  // 超时
  timeout: 5 * 60 * 1000,
});

// 添加请求拦截器
http.interceptors.request.use(
  config => {
    const token = JSON.parse(localStorage.getItem("PangHu") || "{}").state?.userToken ?? "";
    token && (config.headers["Authorization"] = `Bearer ${token}`);
    return config;
  },
  error => {
    console.log("🚀 ~ error:", error);
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
http.interceptors.response.use(
  response => {
    const data = response.data;
    if (data.code !== 200) {
      return Promise.reject(data);
    }
    return data === undefined ? {} : data;
  },
  error => {
    console.log("🚀 ~ error:", error);
    message.error(error.message || "未知错误~");
    if (error.status === 401) {
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);

export default http;
